"""
@author: zwz
@file: 05.三乐购物系统.py
@time: 2022/11/16 0016 10:58:08
"""
# 4、写一个三乐购物系统
     #  欢迎提示语
     #1、登录
        #1、查看商品列表（ 种类  ，价钱）
     #2、注册  -- 文件   用户名，密码，账号余额

# import json
# user = {}
# num1 = 1
#
# def shopping():
#     commodity = {"苹果":3, "橘子":5, "梨子":4, "葡萄":6, "芒果":8, "西瓜":15}
#     for key, value in commodity.items():
#         print(key, " ￥", value)
#
#
# def regist():
#     print("注册".center(30,"-"))
#     with open('用户信息.txt', 'a') as file:
#         username = input("请输入用户名：")
#         passwd = input("请输入密码：")
#         money = input("请输入金额：")
#         user[username] = {"passwd": passwd, "money": money}
#         file.write(json.dumps(user))
#         file.write('\n')
#         print("注册成功")
#         print("-"*60)
#
#
# def login(username, passwd):
#
#     user_message = open("用户信息.txt", 'r')
#     lines = user_message.readlines()
#     message = {}
#     for line in lines:
#         message_1 = eval(line)
#         message = dict(message, **message_1)
#     if username in message and passwd == message[username]['passwd']:
#         print("登录成功")
#         print(f"欢迎光临！你的余额为：{message[username]['money']}")
#         return True
#     elif username in message and passwd != message[username]['passwd']:
#         print("密码错误")
#     else:
#         num3 = input("用户不存在，按 1 注册:")
#         if num3 == "1":
#             regist()
#
# print("欢迎进入三乐购物系统".center(50,"-"))
# while True:
#     print("1、登录".center(50))
#     print("2、注册".center(50))
#     print("3、退出".center(50))
#     num = input("请选择您需要的操作：")
#     if num == "1":
#         print("登录".center(30, "-"))
#         username = input("请输入用户名：")
#         passwd = input("请输入密码：")
#         if login(username, passwd):
#             num2 = input("输入1查看商品列表,其它退出:")
#             if num2 == "1":
#                 print("商品列表".center(30,"-"))
#                 shopping()
#                 break
#             else:
#                 break
#     elif num == "2":
#         regist()
#     elif num == "3":
#         break
#     else:
#         print("请输入 1 或 2 或 3")

import json

# 用户信息：用户名 密码 余额
# user = {"sc": {"passwd": "123456", "money": 99999999}}
# 商品信息：价格 名字 编号
products = [["苹果", 5], ["香蕉", 3], ["葡萄", 8], ["榴莲", 40]]
# 购物车：用户名 商品编号 数量
# car = {"用户名":[[0, 2], [1, 2]]}
car = {}

# 从文件获取用户信息
def message():
    with open("用户信息.txt", 'r') as user_message:
        lines = user_message.readlines()
        user = {}
        for line in lines:
            message_1 = eval(line)
            user = dict(user, **message_1)
        return user

# 登录
def login(name, passwd):
    user = message()
    # 判断用户信息是否正确
    if name in user and passwd == user[name]["passwd"]:
        return True

# 注册
def regist(name1, passwd1, money1):
    # user = {"sc": {"passwd": "123456", "money": 99999999}}
    user = message()
    if name1 not in user.keys():
        # user.update({name1: {"passwd": passwd1, "money": money1}})
        user1 = {}
        with open("用户信息.txt", 'a') as user_message:

            user1[name1] = {"passwd": passwd1, "money": money1}
            # print(user1)
            user_message.write(json.dumps(user1))
            user_message.write('\n')
        print("注册成功")
        print("-"*60)
        return True
    else:
        print("用户名已存在！")

# 菜单
def menu():
    print("-" * 50)
    print("1、查看商品列表")
    print("2、添加到购物车")
    print("3、结算")
    print("4、退出")
# 商品列表
def show_goods():
    print("编号".ljust(10, " "), "名称".ljust(10, " "), "价格".ljust(10, " "))
    for index, pro in enumerate(products):
        print(str(index).ljust(11, " "), pro[0].ljust(10, " "), str(pro[1]).ljust(10, " "))

# 购物车
def add_car(name, product_id, nums):
    # car = {"用户名":[[0, 2], [1, 2]]}
    if name not in car:
        car[name] = []
    car[name].append([product_id, nums])

# 结算
def checkout(name):
    # user = {"sc": {"passwd": "123456", "money": 0}}
    user =message()
    m1 = user[name]["money"]
    csr_list = car[name]
    total = 0
    print("-"*50)
    print("编号   ", "名称   ", "单价   ", "数量   ", "总价   ")
    for pro in csr_list:
        pro_name = products[pro[0]][0]
        price = products[pro[0]][1] * pro[1]
        pro_total = price * pro[1]
        total += pro_total
        print(str(pro[0]).ljust(6, " "), str(pro_name).ljust(5, " "), str(price).ljust(6, " "), str(pro[1]).ljust(6, " "), str(pro_total).ljust(5, " "))
    print("共计：", total)
    if m1 >= total:
        m1 -= total
    else:
        print("余额不足！")
    user[name]["money"] = m1

def home():
    print("1.登录")
    print("2.注册")
    print("3.退出")

print("欢迎来到三乐购物系统：".center(50, "*"))
home()
while 1:
    options = input("请选择您需要的操作：")
    if options == "1":
        name = input("请输入用户名：")
        passwd = input("请输入密码：")
        if login(name, passwd):
            while 1:
                menu()
                op = input("请输入你的选择：")
                if op == "1":
                    show_goods()
                elif op == "2":
                    product_id = input("请输入要购买的商品编号：")
                    if product_id.isdigit() and 0<=int(product_id)<len(products):
                        nums = int(input("请输入要购买的数量："))
                        add_car(name, int(product_id), nums)
                elif op == "3":
                    checkout(name)
                elif op == "4":
                    home()
                    break
        else:
            print("登录失败！用户名或密码错误")


    elif options == "2":
        name1 = input("请输入用户名：")
        passwd1 = input("请输入密码：")
        money1 = int(input("请输入您的余额："))
        regist(name1, passwd1, money1)
        home()
    elif options == "3":
        break
    else:
        print("输入无效")

